#include "../fifo.h"


void server(int,int);

int main(int argc,char * argv)
{
	int readfifo,writefifo,dummyfd,fd;
	char *ptr,buff[MAXLINE+1],fifoname[MAXLINE];
//	ptr=NULL;
	pid_t pid;
	ssize_t n;
	if((mkfifo(SERVFIFO,FILE_MODE)<0)&&(errno!=EEXIST))
	{
		//err_sys("can't");
	}

	while((readfifo = open(SERVFIFO,O_RDONLY))<0)
	{
		if(errno != EINTR)
		{
		
		}	
	}

	while((dummyfd = open(SERVFIFO,O_WRONLY))<0)
	{
		if(errno != EINTR)
		{
			
		}
	}
	while(1)
	{
		while((n = read(readfifo,buff,MAXLINE)<0))
		{
			if( errno != EINTR&&errno !=  EAGAIN)
			{

			}
		}

		if(buff[n-1] =='\n')
			n--;
		buff[n]='\0';
		if((ptr=strchr(buff,' '))==NULL)
		{
			perror("strch()");
			continue;
		}
		*ptr++ = 0;
		pid = atol(buff);
		snprintf(fifoname,sizeof(fifoname),"/tmp/fifo.%ld",(long)pid);
		if((writefifo=open(fifoname,O_WRONLY))<0)
		{
			perror("writefifo open()");
			continue;
		}
		
		while((fd=open(ptr,O_RDONLY))<0)
		{
			if(errno == EINTR)	
				continue;
			snprintf(buff+n,sizeof(buff)-n,"can't open,%s \n",strerror(errno));	
			n = strlen(ptr);
			write(writefifo,ptr,n);
			close(writefifo);
			break;
		}
		if(fd>0)
		{
			while((n=read(fd,buff,MAXLINE))>0)
			{
				write(writefifo,buff,n);
			}
			close(fd);
			close(readfifo);
		}
		break;
	}
	exit(0);
}
